/**
*	@file QueryThread.cpp
*
*	@brief this file implements class for query thread
*
*	@author li yuchen
*
*	@date 1/28/2011
*/

#include "QueryThread.h"
#include "QueryEvaulator.h"
#include "Utility.h"
#include <iostream>
#include <time.h>
using namespace std;

bool query_thread_global_stop = false;

CRITICAL_SECTION QueryThread::lock_affects_left;
CRITICAL_SECTION QueryThread::lock_affects_right;
CRITICAL_SECTION QueryThread::lock_next;
CRITICAL_SECTION QueryThread::lock_next_bip;
int QueryThread::total_thread_num_ = 0;


unsigned int __stdcall RunThread(void* data){
	QueryThread* tp = (QueryThread*)data;
	tp->QueryExecution();
	return 0;
}

QueryThread::QueryThread() {
	this->thread_handle_ = NULL;
	this->thread_num_ = total_thread_num_;
	total_thread_num_++;
}

QueryThread::~QueryThread() {
	if(this->thread_handle_ != NULL){
		CloseHandle(this->thread_handle_);
	}
	query_thread_global_stop = false;
	total_thread_num_ = 0;
}


void QueryThread::QueryExecution() {
	NonBoolEvaluation(this->thread_num_);
	/*if(this->thread_num_ == 0) ThreadTest1(this);
	else  if(this->thread_num_ == 1) ThreadTest2(this);*/
}

void QueryThread::Join(){
	WaitForSingleObject(this->thread_handle_, INFINITE);
	//WaitForMultipleObjects(3, handles, true, INFINITE); //"Join" threads
}


/** start()
  * creates a low-level thread object and calls the
  * run() function
**/ 
void QueryThread::Start() {
	this->thread_handle_ = (HANDLE)_beginthreadex(0, 0, &RunThread,(QueryThread*)this, 0, 0);
}

/** stop()
  * stops the running thread and frees the thread handle
**/ 
void QueryThread::Stop() {
	if(this->thread_handle_ == NULL) return;	
	WaitForSingleObject(thread_handle_,INFINITE);
	CloseHandle(thread_handle_);
	thread_handle_ = NULL;
}



